package com.zyz.common.utils.word;

import com.zyz.common.utils.StringUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;


/**
 * @author xuhao
 * @date 2021-04-06
 * @description word转html工具类
 */
public class Word2HtmlUtil {

    public static final String SPECIAL_STR = "SHARE";

    private static final String ENCODING = "UTF-8";

    /**
     * 功能描述: 替换模板变量为input框
     *
     * @param str
     * @return java.lang.String
     * @author xuhao
     */
    private static String replaceSpecialStr(String str) {
        if (StringUtils.isEmpty(str)) {
            return str;
        }
        String beginStr = "<div>";
        String backStr = str.substring(str.indexOf(">") + 1, str.length());
        str = beginStr + backStr;
        if (!str.contains(SPECIAL_STR)) {
            return str;
        }
        StringBuffer destStr = new StringBuffer();
        String ss[] = str.split(SPECIAL_STR);
        for (int i = 0; i < ss.length - 1; i++) {
            destStr.append(ss[i] + "<input value=\"\" id=\"" + (i + 1)
                    + "\" name=\"txt\" type=\"text\" style=\"border: 1px solid #d7d7d7; height: 30px; line-height: 30px; margin-top: 4px; width: 230px;\" AUTOCOMPLETE=\"off\" />");
        }
        destStr.append(ss[ss.length - 1]);
        return destStr.toString();
    }

    public static String convert2007ToStr(String root, String file) throws Exception {
        return replaceSpecialStr(convert2007(root, file));
    }


    public static String convert2007(String root, String file) throws IOException {
        if (StringUtils.isEmpty(file) || !file.contains(File.separator) || !file.contains(".")) {
            return null;
        }
        String filepath = file.substring(0, file.lastIndexOf(File.separator) + 1);
        String fileName = file.substring(file.lastIndexOf(File.separator) + 1, file.lastIndexOf("."));
        //String htmlName = fileName+".html";
        String imagepath = filepath + fileName;
        File f = new File(root + file);
        if (!f.exists()) {
            return null;
        }
        if (f.getName().endsWith(".docx") || f.getName().endsWith(".DOCX")) {
            // 1) 加载word文档生成 XWPFDocument对象
            InputStream in = new FileInputStream(f);
            XWPFDocument document = new XWPFDocument(in);
            // 2) 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)
            File imageFolderFile = new File(root + imagepath);
            /*if (!imageFolderFile.exists()) {
                imageFolderFile.mkdir();
            }*/
            XHTMLOptions options = XHTMLOptions.create().URIResolver(new BasicURIResolver(imagepath));
            options.setExtractor(new FileImageExtractor(imageFolderFile));
            options.setIgnoreStylesIfUnused(false);
            options.setFragment(true);
            // 3) 将 XWPFDocument转换成XHTML
            /*OutputStream out = new FileOutputStream(new File(filepath + htmlName));
            XHTMLConverter.getInstance().convert(document, out, options);*/
            //也可以使用字符数组流获取解析的内容
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XHTMLConverter.getInstance().convert(document, baos, options);
            String content = new String(baos.toByteArray(), ENCODING);
            baos.close();
            return content;
        }
        return null;
    }

    /**
     * /**
     * 2003版本word转换成html
     *
     * @throws IOException
     * @throws TransformerException
     * @throws ParserConfigurationException
     */
    public static String convert2003(String file)
            throws IOException, TransformerException, ParserConfigurationException {
        if (StringUtils.isEmpty(file) || !file.contains(File.separator) || !file.contains(".")) {
            return null;
        }
        String filepath = file.substring(0, file.lastIndexOf(File.separator) + 1);
        String fileName = file.substring(file.lastIndexOf(File.separator) + 1, file.lastIndexOf("."));
        //String htmlName = fileName+".html";
        final String imagepath = filepath + fileName;
        File f = new File(file);
        if (!f.exists()) {
            return null;
        }
        if (f.getName().endsWith(".doc") || f.getName().endsWith(".DOC")) {
            InputStream input = new FileInputStream(new File(file));
            HWPFDocument wordDocument = new HWPFDocument(input);
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                    DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
            //设置图片存放的位置
            wordToHtmlConverter.setPicturesManager(new PicturesManager() {
                @Override
                public String savePicture(byte[] content, PictureType pictureType, String suggestedName,
                                          float widthInches, float heightInches) {
                    File imgPath = new File(imagepath);
                    if (!imgPath.exists()) {//图片目录不存在则创建
                        imgPath.mkdirs();
                    }
                    File file = new File(imagepath + suggestedName);
                    try {
                        OutputStream os = new FileOutputStream(file);
                        os.write(content);
                        os.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return imagepath + suggestedName;
                }
            });

            //解析word文档
            wordToHtmlConverter.processDocument(wordDocument);
            Document htmlDocument = wordToHtmlConverter.getDocument();

            /*File htmlFile = new File(filepath + htmlName);
            OutputStream outStream = new FileOutputStream(htmlFile);*/

            //也可以使用字符数组流获取解析的内容
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            OutputStream outStream = new BufferedOutputStream(baos);

            DOMSource domSource = new DOMSource(htmlDocument);
            StreamResult streamResult = new StreamResult(outStream);

            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer serializer = factory.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");

            serializer.transform(domSource, streamResult);

            //也可以使用字符数组流获取解析的内容
            String content = new String(baos.toByteArray(), ENCODING);
            baos.close();
            outStream.close();
            return content;
        }
        return null;
    }
}
